#include "PeashooterPlayer.h"
#include "Animation.h"
#include  "Timer.h"
#include "PeaBullet.h"
PeashooterPlayer::PeashooterPlayer(bool facing_right) :Player(facing_right)
{

	animation_idle_left->Set_Atlas(&atlas_peashooter_idle_left);
	animation_idle_right->Set_Atlas(&atlas_peashooter_idle_right);
	animation_run_left->Set_Atlas(&atlas_peashooter_run_left);
	animation_run_right->Set_Atlas(&atlas_peashooter_run_right);
	animation_attack_ex_left->Set_Atlas(&atlas_peashooter_attack_ex_left);
	animation_attack_ex_right->Set_Atlas(&atlas_peashooter_attack_ex_right);
	animation_die_left->Set_Atlas(&atlas_peashooter_die_left);
	animation_die_right->Set_Atlas(&atlas_peashooter_die_right);

	animation_idle_left->Set_interval(75);
	animation_idle_right->Set_interval(75);
	animation_run_left->Set_interval(75);
	animation_run_right->Set_interval(75);
	animation_attack_ex_left->Set_interval(75);
	animation_attack_ex_right->Set_interval(75);
	animation_die_left->Set_interval(150);
	animation_die_right->Set_interval(150);

	animation_die_left->Set_loop(false);
	animation_die_right->Set_loop(false);

	size.x = 96; size.y = 96;

	timer_attack_ex = new Timer();
	timer_spawn_pea_ex = new Timer();

	timer_attack_ex->Set_Wait_Time(attack_ex_duration);
	timer_attack_ex->Set_One_Shot(true);
	timer_attack_ex->Set_Callback([&]() { is_attacking_ex = false; });

	timer_spawn_pea_ex->Set_Wait_Time(100);
	timer_spawn_pea_ex->Set_Callback([&]() { spawn_pea_bullet(speed_pea_ex); });

	attack_cd = 100;
}

void PeashooterPlayer::on_update(int delta)
{
	Player::on_update(delta);

	if (is_attacking_ex)
	{
		Main_Camera.Shake(5, 100);
		timer_attack_ex->on_update(delta);
		timer_spawn_pea_ex->on_update(delta);
	}
}

void PeashooterPlayer::on_attack()
{
	spawn_pea_bullet(speed_pea);
	switch (rand()%2)
	{
	case 0:
		mciSendString(_T("play pea_shoot_1 from 0"), NULL, 0, NULL);
		break;
	case 1:
		mciSendString(_T("play pea_shoot_2 from 0"), NULL, 0, NULL);
		break;
	}
}

void PeashooterPlayer::on_attack_ex()
{
	is_attacking_ex = true;
	timer_attack_ex->Restart();

	is_faceing_right ? animation_attack_ex_right->Reset() : animation_attack_ex_left->Reset();

	mciSendString(_T("play pea_shoot_ex from 0"), NULL, 0, NULL);
}

void PeashooterPlayer::spawn_pea_bullet(float speed)
{
	Bullet* bullet = new PeaBullet();

	Vector2 bullet_position, bullet_velocity;
	const Vector2& bullet_size = bullet->get_size();
	bullet_position.x = is_faceing_right
		? position.x + size.x - bullet_size.x / 2
		: position.x - bullet_size.x / 2;
	bullet_position.y = position.y;
	bullet_velocity.x = is_faceing_right ? speed : -speed;
	bullet_velocity.y = 0;

	bullet->set_position(bullet_position.x, bullet_position.y);
	bullet->set_velocity(bullet_velocity.x, bullet_velocity.y);

	bullet->set_collied_target(id == PlayerID::P1 ? PlayerID::P2 : PlayerID::P1);

	bullet->set_callback([&]() { Mp += 15; });

	Bullets.push_back(bullet);
}
